package websocket

import (
	"github.com/fasthttp/websocket"
	"kop/framework/broker"
	"kop/util/log"
	"time"
)

type Conn struct {
	Chan chan []byte
	Conn *websocket.Conn
	Done chan bool
	//deadline time.Duration
	LiveTime time.Time

	Subscribers broker.Subscribers
}

func (c *Conn) Init() {

	c.Chan = make(chan []byte, 3)
	c.Done = make(chan bool, 1)
	c.LiveTime = time.Now()
	//c.deadline = 60

	c.Conn.SetPingHandler(c.PingHandler)
	c.Conn.SetPongHandler(c.PongHandler)

	c.Subscribers = broker.NewSubscribers()
	//go c.Read()
}

func (c *Conn) Close() {

	//_ = c.Conn.Close()
	//close(c.Chan)
	//close(c.done)
	c.Subscribers.Unsubscribe()
}

func (c *Conn) Write(data []byte) error {

	//defer func() {
	//	if err := recover(); err != nil {
	//		log.Error("write msg error: %v", err)
	//	}
	//}()

	return c.Conn.WriteMessage(websocket.BinaryMessage, data)
}

//func (c *Conn) SetDeadline(duration time.Duration) {
//	c.deadline = duration
//}

func (c *Conn) WhatEver() {

	var ticker = time.NewTicker(time.Second * 3)

	for {
		select {
		case msg := <-c.Chan:

			if err := c.Write(msg); err != nil {
				log.Error(err.Error())
			}

		case <-ticker.C:

			if time.Now().Sub(c.LiveTime) > 60*time.Minute {
				log.Info("time.Now().Sub(c.LiveTime) > 60*time.Minute: timeout")
				return
			}

		case <-c.Done:
			return
		}
	}
}

func (c *Conn) PingHandler(s string) error {

	c.LiveTime = time.Now()
	return c.Conn.WriteControl(websocket.PongMessage, []byte{}, c.LiveTime.Add(time.Second))
}

func (*Conn) PongHandler(s string) error {
	return nil
}
